﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AESyouhua
{
    class P_AESdecryption
    {
        private static char[] alphabet = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

        public static int[,] kuozhanmiyao(string keytext)
        {
            int[,] key = KeyExpansion.GetKeyExpansion(keytext);
            return key;
        }

        public static StringBuilder P_Dncryption(string miwen, int[,] key)
        {
            int lun = key.GetLength(0);
            int changdu = key.GetLength(1);
            int[,] cipherKey = new int[lun, changdu];
            int[] key1 = new int[changdu];
            for (int i = 0; i < changdu; i++)
            {
                cipherKey[0, i] = key[0, i];
                cipherKey[lun - 1, i] = key[lun - 1, i];
            }

            for (int i = 1; i < lun - 1; i++)
            {
                for (int j = 0; j < changdu; j++)
                {
                    key1[j] = key[i, j];
                }
                key1 = MixColumn.InvMixColumn(key1);
                for (int j = 0; j < changdu; j++)
                {
                    cipherKey[i, j] = key1[j];
                }
            }
            int[,] plain = Decryption.Getdecryption(miwen.ToString(), cipherKey);
            StringBuilder strB1 = new StringBuilder();
            StringBuilder s1 = new StringBuilder();
            byte[] result = new byte[plain.GetLength(0) * 16];

            for (int i = 0; i < plain.GetLength(0); i++)
            {
                for (int j = 0; j < 16; j++)
                {
                    for (int h = 7; h >= 0; h--)
                    {
                        s1.Append(plain[i, j] >> h & 1);
                    }
                }
            }
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = Convert.ToByte(s1.ToString(i * 8, 8), 2);
            }
            strB1.Append(Encoding.Default.GetString(result)).Replace(" ", ""); ;

            Console.WriteLine("解密后的密文为：{0}", strB1.ToString().Replace(" ", ""));
            return strB1;
        }
    }
}
